﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace AudioBook.AudioManagement.FileManage
{
    public partial class AddFile : System.Web.UI.Page
    {
        #region Private methods

        private bool SaveFileAndFolder()
        {
            string currentFolder = GlobalParam.RootFileFolder + hidCurrentFolder.Value;
            if (Directory.Exists(currentFolder))
            {
                try
                {
                    if (!string.IsNullOrEmpty(txtFolder.Text))
                    {
                        string newFolder = currentFolder + txtFolder.Text;
                        Directory.CreateDirectory(newFolder);
                    }

                    if (fulFile.HasFile)
                    {
                        string fileName = currentFolder + fulFile.FileName.Substring(fulFile.FileName.LastIndexOf("\\") + 1);
                        if (!chkOveride.Checked && File.Exists(fileName))
                        {
                            valCommon.ErrorMessage = "Upload file is existed, rename the file on the client first.";
                            valCommon.IsValid = false;
                            return false;
                        }
                        else
                        {
                            fulFile.SaveAs(fileName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    valCommon.IsValid = false;
                    valCommon.ErrorMessage = ex.Message;
                    return false;
                }
            }
            else
            {
                Response.Redirect(GUIConstants.WebPage.FilePage.DefaultFile);
            }
            return true;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString[GUIConstants.Common.ID_QUERY] != null)
            {
                hidCurrentFolder.Value = Request.QueryString[GUIConstants.Common.ID_QUERY];
                txtCurrentFolder.Text = hidCurrentFolder.Value;
            }
        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            bool result = SaveFileAndFolder();
            if (result)
            {
                Response.Redirect(GUIConstants.WebPage.FilePage.DefaultFile + "?id=" + hidCurrentFolder.Value);
            }
        }

        protected void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            bool result = SaveFileAndFolder();
            if (result)
            {
                Response.Redirect(Request.Url.ToString());
            }
        }
    }
}
